class Solution {
public:
    std::vector<std::vector<int>> allPathsSourceTarget(std::vector<std::vector<int>>& graph) {
        std::vector<std::vector<int>> ret;
        std::stack<std::pair<int, std::vector<int>>> s;
        int n = graph.size() - 1;

        // Initialize stack with the starting node (0) and path {0}
        s.push({ 0, {0} });

        while (!s.empty()) {
            auto [cur, path] = s.top();
            s.pop();

            if (cur == n) {
                ret.push_back(path);
                continue;
            }

            for (auto it = graph[cur].rbegin(); it != graph[cur].rend(); ++it) {
                path.push_back(*it);
                s.push({ *it, path });
                path.pop_back();
            }
        }

        return ret;
    }
};